<?php

class IndexController extends Zend_Controller_Action
{

    public function init()
    {
        $users = new Application_Model_DbTable_Users();
        $this->view->users = $users->fetchAll();
    }

    public function indexAction()
    {
        // action body
    }

    public function addAction()
    {
        $form = new Application_Form_User();
        
        $form->submit->setLabel('Add');       
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $username = $form->getValue('username');
                $email = $form->getValue('email');
                $password = $form->getValue('password');
                $users = new Application_Model_DbTable_Users();
                $users->addUser($username, $email, $password);
                $this->_helper->redirector('index');
            } else {
                $form->populate($formData);
            }
        }
    
    }

    public function editAction()
    {
        $form = new Application_Form_User();
        $form->submit->setLabel('Save');
        $this->view->form = $form;
        
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
                if ($form->isValid($formData)) {
                $id = (int) $form->getValue('id');
                $username = $form->getValue('username');
                $email = $form->getValue('email');
                $password = $form->getValue('password');
                $users = new Application_Model_DbTable_Users();
                $users->updateUser($id, $username, $email, $password);
                
                  $this->_helper->redirector('index');
            } else {
                $form->populate($formData);
            }
         }else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $users = new Application_Model_DbTable_Users();
                $form->populate($users->getUser($id));
            }
        }
    }

    public function deleteAction()
    {
        if ($this->getRequest()->isPost()) {
            $del = $this->getRequest()->getPost('del');
            if ($del == 'Yes') {
                $id = $this->getRequest()->getPost('id');
                $users = new Application_Model_DbTable_Users();
                $users->deleteUser($id);
            }
            $this->_helper->redirector('index');
        } else {
            $id = $this->_getParam('id', 0);
            $users = new Application_Model_DbTable_Users();
            $this->view->user = $users->getUser($id);
        }
    }


}







